const fs = require('fs');
const path = require('path');

const directoryPath = './src'; // 替换为你要统计的文件夹路径

// 递归统计文件夹内所有文件的行数
function countLinesInFile(filePath) {
	return new Promise((resolve, reject) => {
		let linesCount = 0;

		const readStream = fs.createReadStream(filePath);

		readStream.on('data', (chunk) => {
			// 计算 chunk 中的行数
			linesCount += chunk.toString().split('\n').length - 1;
		});

		readStream.on('end', () => {
			resolve(linesCount);
		});

		readStream.on('error', (err) => {
			reject(err);
		});
	});
}

async function countLinesInDirectory(dir) {
	try {
		const files = await fs.promises.readdir(dir);
		let totalLines = 0;

		for (const file of files) {
			const filePath = path.join(dir, file);
			const stat = await fs.promises.stat(filePath);

			if (stat.isDirectory()) {
				// 如果是目录，递归调用
				totalLines += await countLinesInDirectory(filePath);
			} else if (stat.isFile()) {
				// 如果是文件，统计行数
				const lines = await countLinesInFile(filePath);
				console.log(`File: ${filePath}, Lines: ${lines}`);
				totalLines += lines;
			}
		}

		return totalLines;
	} catch (err) {
		console.error(`Error reading directory: ${err.message}`);
	}
}

// 调用函数并输出结果
countLinesInDirectory(directoryPath)
	.then(totalLines => {
		console.log(`Total lines in directory "${directoryPath}": ${totalLines}`);
	})
	.catch(err => {
		console.error(`Error counting lines: ${err.message}`);
	});
